package com.lqk.netty.groupchat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class GroupChatClient {

    // 属性
    private final String host;

    private final int port;
    private final String username;

    public GroupChatClient(String host, int port, String username) {
        this.host = host;
        this.port = port;
        this.username = username;
    }

    public void run() throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 得到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            // 加入相关的 Handler
                            // 解码器
                            pipeline.addLast("decoder",new StringDecoder());
                            // 编码器
                            pipeline.addLast("encoder",new StringEncoder());
                            // 加入自定义的 Handler
                            pipeline.addLast(new GroupChatClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            // 提示信息，得到channel
            Channel channel = channelFuture.channel();
            System.out.println("-------" + channel.localAddress() + "-------");
            System.out.println("#################################################");
            System.out.println("~~~~~~~~~~~~~~#端口号#消息内容~~这样可以给单独一个用户发消息~~~~~~~~~~~~~~~~~~");
            System.out.println("#################################################");
            // 客户端需要输入信息，创建一个扫描器
            Scanner sc = new Scanner(System.in);
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            while (sc.hasNextLine()){
                String msg = sc.nextLine();
                // 通过 channel 发送到服务器端
                channel.writeAndFlush("["+username+"]: "+msg + "\r\n");
            }
            // 监听关闭事件
            channelFuture.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }
}
